package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.merchanth5.service.acs.ExternalOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author: CKQ
 * @DateTime: 2020/9/23 17:17
 * @Description: 用于给蓝美推送重试推送信息
 */
@Component
@Async
@Slf4j
public class LmNotifyTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ExternalOrderService externalOrderService;

    @RedisLock("LmNotifyTask")
    @Scheduled(cron = "0 0/15 * * * ?")
    public void runTask() {
        Long count = stringRedisTemplate.opsForList().size("lm_task_list:");
        LOGGER.info("蓝美通知失败重试任务开始");
        if (count > 0) {
            for (Long i = 0L; i < count; i++) {
                String result = stringRedisTemplate.opsForList().leftPop("lm_task_list:");
                if (!StringUtils.isEmpty(result)) {
                    Map<String, Object> orderMap = (Map<String, Object>) JSON.parse(result);
                    if (orderMap != null) {
                        Integer sendNum = Integer.valueOf(orderMap.get("sendNum").toString()) + 1;
                        if (sendNum < 4) {
                            LOGGER.info("蓝美通知失败重试任务调用开始：orderSn:"+orderMap.get("orderSn").toString()+"，snedNum："+sendNum);
                            externalOrderService.summaryEnd(orderMap.get("orderSn").toString(), sendNum);
                        }
                    }
                }
            }
        }
    }
}
